using Zhaoxi.Zhihu.Core.AppUserAggregate.Entites;
using Zhaoxi.Zhihu.Core.AppUserAggregate.Specification;

using Zhaoxi.Zhihu.Core.Interface;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Repositoy;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;
using Zhaoxi.Zhihu.UseCases.Common.Interface;
using Zhaoxi.Zhihu.UseCases.Common.Queries.Interfaces;

namespace Zhaoxi.Zhihu.UseCases.AppUsers.Commands;
[Authorize]
public record CreateFollowQuestionCommand(int QuestionId) : ICommand<IResult>;
    
public class CreateFollowQuestionCommandHandler (
    IRepository<AppUser> userRepo,
    IFollowQuestionService followQuestionService,
     IUser user ): ICommandHandler<CreateFollowQuestionCommand, IResult>
{
    public async Task<IResult> Handle(CreateFollowQuestionCommand request, CancellationToken cancellationToken)
    {
        var spec=new FollowQuestionByIdSpec(user.Id!.Value,request.QuestionId);
        var appuser=await userRepo.GetSingleOrDefaultAsync(spec,cancellationToken);
        if (appuser == null) return Result.NotFound("用户不存在");
        var result=await followQuestionService.FollowAsync(appuser,request.QuestionId,cancellationToken);

        if (!result.IsSuccess)return result;
        await userRepo.SaveChangesAsync(cancellationToken);
        
        return Result.Success();
    }
}